package com.ajk.server.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ajk.message.model.req.EaseRegisterUserReq;
import com.ajk.message.service.EasemobService;
import com.ajk.server.dao.AjkAccountMapper;
import com.ajk.server.dao.DictionaryMapper;
import com.ajk.server.dao.EaseUserMapper;
import com.ajk.server.dao.UsersMapper;
import com.ajk.server.model.AjkAccount;
import com.ajk.server.model.Dictionary;
import com.ajk.server.model.EaseUser;
import com.ajk.server.model.Users;
import com.ajk.server.service.AjkAccountService;
import com.ajk.server.service.EasemobMessageService;

@Service
public class EasemobMessageServiceImpl implements EasemobMessageService {
	Logger logger = LoggerFactory.getLogger(EasemobMessageServiceImpl.class);
	
	@Autowired
	EaseUserMapper easeUserMapper;
	
	@Autowired
	EasemobService easemobService;
	
	@Autowired
	DictionaryMapper dictionaryMapper;
	
	@Autowired
	UsersMapper usersMapper;
	
	@Autowired
	AjkAccountMapper ajkAccountMapper;
	
	@Autowired
	AjkAccountService ajkAccountService;
	
	@Override
	public EaseUser findByEaseUserByUserId(Integer userId){
		EaseUser user = easeUserMapper.findByUserId(userId);
		if(user==null){
			List<Dictionary> dictionarys = dictionaryMapper.findByKey("easemod_chat_doctor_list");
			String dictValue = dictionarys.get(0).getDictValue();
			String[] idStrings = dictValue.split(",");
			
			Users my = usersMapper.findById(userId);
			AjkAccount myAccount = ajkAccountMapper.findByUserId(userId);
			logger.info("环信账号 : {}",myAccount);
			if(myAccount==null){
				logger.info("注册环信账号之前 : " + System.currentTimeMillis());
				myAccount = ajkAccountService.createAndInsertAccount(userId, my.getRole());
				logger.info("注册环信账号之后 : " + System.currentTimeMillis());
			}
			
			//创建easeUser
			user = new EaseUser();
			user.setNickname(my.getName());
			user.setPassword(myAccount.getAccessId());
			user.setUsername(userId.toString());
			user.setUserId(userId);	
			easeUserMapper.insert(user);
			
			//注册环信账号
			EaseRegisterUserReq req = new EaseRegisterUserReq();
			req.setNickname(my.getName());
			req.setPassword(myAccount.getAccessId());
			req.setUsername(userId.toString());
			logger.info("注册环信账号之");
			String registerResult = easemobService.registerUser(req);
			logger.info("注册环信账号返回结果：{}",registerResult);
			//创建朋友关系
			for (String string : idStrings) {
				easemobService.addFriend(userId.toString(), string);
			}
		}
		return user;
	}

}
